import React, {useEffect, useLayoutEffect, useRef, useState} from 'react';
import {FlatList, StyleSheet, Text, View} from 'react-native';
import {defaultNavigationConfigure} from "../../base/navconfig";
import {LoadingView} from "react-native-gzdsx-elements";
import {ListItem} from "react-native-elements";
import moment from "moment";
import {useNavigation} from "@react-navigation/native";
import ApiService from "../../utils/ApiService";
import StatusBarCtl from "../../utils/StatusBarCtl";
import Empty from "../../components/Empty";

const NotificationIndex = () => {
    const navigation = useNavigation();

    const [dataList, setDataList] = useState([]);
    const [total, setTotal] = useState(0);
    const [loading, setLoading] = useState(true);
    const [refreshing, setRefreshing] = useState(false);
    const [loadingMore, setLoadingMore] = useState(false);

    const offset = useRef(0);
    const requesting = useRef(false);

    const fetchData = () => {
        ApiService.get('/notifications', {
            params: {
                offset: offset.current,
                limit: 15
            }
        }).then(response => {
            let {items} = response.result;
            if (loadingMore) {
                setDataList(dataList.concat(items));
            } else {
                setDataList(items);
            }
        }).finally(() => {
            requesting.current = false;
            setLoading(false);
            setRefreshing(false);
            setLoadingMore(false);
        })
    }

    useLayoutEffect(() => {
        navigation.setOptions({
            ...defaultNavigationConfigure(navigation),
            title: '消息',
            headerLeft: () => null
        });

        return navigation.addListener('focus', () => {
            StatusBarCtl.setToDarkStyle();
        });
    }, [navigation]);

    useEffect(() => {
        fetchData();
    }, []);

    useEffect(() => {
        if (refreshing) {
            offset.current = 0;
            fetchData();
        }
    }, [refreshing]);

    useEffect(() => {
        if (loadingMore) {
            offset.current += 15;
            fetchData();
        }
    }, [loadingMore]);

    const onRefresh = () => {
        if (requesting.current) {
            return false;
        }

        setRefreshing(true);
    }

    const onEndReached = () => {
        if (requesting.current) {
            return false;
        }

        if (dataList.length === total) {
            return false;
        }

        setLoadingMore(true);
    }

    if (loading) {
        return <LoadingView/>;
    }

    return (
        <FlatList
            data={dataList}
            keyExtractor={(item, index) => index.toString()}
            renderItem={({item, index}) => (
                <ListItem containerStyle={styles.row}>
                    <ListItem.Content>
                        <View style={{flexDirection: 'row'}}>
                            <ListItem.Title style={styles.from}>{item.data.from}</ListItem.Title>
                            <Text style={styles.time}>{moment(item.updated_at).format('yy/M/D')}</Text>
                        </View>
                        <ListItem.Subtitle style={styles.message}>{item.data.message}</ListItem.Subtitle>
                    </ListItem.Content>
                </ListItem>
            )}
            ListEmptyComponent={
                <Empty description={'没有任何消息'} style={{height: 300}}/>
            }
            refreshing={refreshing}
            onRefresh={onRefresh}
            onEndReachedThreshold={0.2}
            onEndReached={onEndReached}
        />
    );
}

export default NotificationIndex;

const styles = StyleSheet.create({
    row: {
        borderBottomWidth: 0.5,
        borderBottomColor: '#e9e9e9',
        paddingVertical: 15
    },
    from: {
        fontSize: 18,
        color: '#333',
        flex: 1
    },
    message: {
        fontSize: 14,
        color: '#666',
        marginTop: 8
    },
    time: {
        fontSize: 14,
        color: '#939393'
    }
})
